package org.csu.mybigpro.persistence;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.csu.mybigpro.domain.Threads;

import java.time.LocalDateTime;

public interface ThreadsMapper extends BaseMapper<Threads> {

    default Page<Threads> selectPageList(int pageNo, int pageSize, String searchKey,String sortBy) {
        Page<Threads> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<Threads> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Threads::getIsDelete,"0");
        if (searchKey != null && !searchKey.isEmpty()) {
            wrapper.like(Threads::getTitle, searchKey);
        }

        if ("last_reply_at".equals(sortBy)) {
            // 最后回复时间倒序
            wrapper.orderByDesc(Threads::getLastReplyAt);
        } else if ("created_at".equals(sortBy)) {
            // 创建时间倒序
            wrapper.orderByDesc(Threads::getCreatedAt);
        }else if("reply_at".equals(sortBy)) {
            wrapper.orderByDesc(Threads::getReplyCount);
        } else {
            // 默认也可以加个兜底排序,防意外的按照创建时间倒序
            wrapper.orderByDesc(Threads::getCreatedAt);
        }

        return selectPage(page, wrapper);
    }

    default int updateReplyTimeAndCount(Long threadId){
        LambdaUpdateWrapper<Threads> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Threads::getId, threadId);
        wrapper.set(Threads::getLastReplyAt, LocalDateTime.now())
                .setSql("reply_count = reply_count + 1");
        return update(wrapper);
    }

    default int updateView(int threadId){
        LambdaUpdateWrapper<Threads> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Threads::getId, threadId)
        .setSql("view_count = view_count + 1");
        return update(null,wrapper);
    }

    default int threadsCount(){
        LambdaQueryWrapper<Threads> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Threads::getIsDelete,"0");
        return Math.toIntExact(selectCount(wrapper));
    }

    default Threads getByThreadId(Long threadId){
        LambdaQueryWrapper<Threads> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Threads::getId, threadId);
        wrapper.eq(Threads::getIsDelete,"0");
        return selectOne(wrapper);
    }
}
